const puppeteer = require('puppeteer-core')

// 获取 webview 并返回其 page 对象
async function getWebviewPage() {
    try {
        const browser = await puppeteer.connect({
            browserURL: 'http://localhost:9222',
            defaultViewport: null
        })
        
        // 等待 webview target 出现
        const webviewTarget = await new Promise((resolve) => {
            const checkTarget = () => {
                const target = browser.targets().find(t => t.type() === 'webview')
                if (target) {
                    resolve(target)
                } else {
                    setTimeout(checkTarget, 100)
                }
            }
            checkTarget()
        })

        // 获取 webview 的 page 对象
        const page = await webviewTarget.page()
        return { success: true, page }
    } catch (error) {
        console.error('获取 webview 失败:', error)
        return { success: false, error: error.message }
    }
}

module.exports = getWebviewPage